<template>
	<scroll-view class="form-container bg" :scroll-y="true">
        <jkFormCard title="基础信息" :show-right-icon="true">
            <u-icon v-if="!ruleForm.auditState" slot="right" name="trash" size="24" @click="onDeleteBtn"></u-icon>
            <jk-form-item label="调拨单号" :show-right-icon="false">
                <view>{{ ruleForm.code || '系统自动生成' }}</view>
            </jk-form-item>
            <!--<jk-form-item label="客户"  @click="selectCustomerPopupOptionState = true" :show-star="true" :value="ruleForm.customerId" @clear="onConfirmOfSelectCustomer(null,{})">
                <view>{{ ruleForm.customerName || '' }}</view>
            </jk-form-item>-->
            <jk-form-item label="输出仓库" @click="onSelectWarehouse('out')" :show-star="true" :value="ruleForm.outWarehouseName" @clear="onClearOutWarehouse">
                <view>{{ ruleForm.outWarehouseName || '' }}</view>
            </jk-form-item>
            <jk-form-item label="输入仓库" @click="onSelectWarehouse('in')" :show-star="true" :value="ruleForm.inWarehouseName" @clear="onClearOutWarehouse">
                <view>{{ ruleForm.inWarehouseName || '' }}</view>
            </jk-form-item>
            <jk-form-item label="调拨时间" @click="onSelectTime('belongDateTime')" :value="ruleForm.belongDateTime" @clear="ruleForm.belongDateTime = ''">
                <view>{{ ruleForm.belongDateTime || '' }}</view>
            </jk-form-item>
            <jk-form-item label="备注" label-position="top" :show-border-bottom="false">
                   <textarea
                       placeholder-class="color4"
                       class="textarea-style"
                       :cursor-spacing="100"
                       style="height: 80rpx;"
                       :adjust-position="true"
                       v-model="ruleForm.remark"
                       placeholder="请输入"
                   ></textarea>
            </jk-form-item>
        </jkFormCard>
        <view
            v-for="(productItem, productIndex) in ruleForm.stockTransferRecordList"
            :key="productIndex"
            class="margin-top-30">
            <jkFormCard :show-right-icon="true">
                <view slot="header" @click="onSeeMoreBtn(productItem)">{{ productItem.productName || '暂无' }}</view>
                <u-icon slot="right" name="scan" size="24" @click="onScanBtn(productIndex)"></u-icon>
                <!--<jk-form-item label="通知单" :show-star="true" :value="productItem.packingPlanCode" @clear="onClearPlanCode(productIndex)" right-icon="edit-pen">
                    <u-input v-model="productItem.packingPlanCode" @blur="onBlurPlanCode($event, productIndex)" confirmType="go" :holdKeyboard="false" :customStyle="{paddingLeft: 0}" :adjustPosition="true" :cursorSpacing="0" type="text" fontSize="28rpx" inputAlign="left" placeholder="通知单" border="surround"></u-input>
                </jk-form-item>-->
                <!--<jk-form-item label="分类" :show-right-icon="false">
                    <view>{{ productItem.categoryName || '' }}</view>
                </jk-form-item>-->
                <!--<jk-form-item label="品种" :show-right-icon="false">
                    <view>{{ productItem.productName || '' }}</view>
                </jk-form-item>-->
                <jk-form-item label="批号" :show-right-icon="true" @click="onSelectProduct(productIndex)">
                    <view>{{ productItem.batchCode || '' }}</view>
                </jk-form-item>
                <!--<jk-form-item label="客户" :show-right-icon="false">
                    <view>{{ productItem.customerName || '' }}</view>
                </jk-form-item>-->
                <jk-form-item label="出库数量" :show-star="true" :value="productItem.outNumber" @clear="productItem.outNumber = ''" right-icon="edit-pen">
                    <u-input v-model="productItem.outNumber" @blur="onTransferNumber($event, 'outNumber', productIndex)" :customStyle="{paddingLeft: 0}" :holdKeyboard="false" :adjustPosition="true" :cursorSpacing="30" type="digit" fontSize="28rpx" inputAlign="left" placeholder="出库数量" border="surround"></u-input>
                </jk-form-item>
                <jk-form-item label="出前库存" :show-right-icon="false">
                    <view>{{ productItem.beforeNumber || '0' }}</view>
                </jk-form-item>
            </jkFormCard>
        </view>
        <view class="flex-center margin-top-20" v-if="!ruleForm.auditState">
            <u-button icon="plus-circle" :disabled="!ruleForm.outWarehouseId" @click="onAddProductBtn">添加</u-button>
        </view>
		<view class="fixed-footer">
            <view style="width: 100%;padding-right: 10rpx;"><u-button style="width: 100%;" @click="onConfirmBtn(0)" :disabled="ruleForm.auditState === 1" :loading="saveLoading" size="large" type="primary">保存</u-button></view>
            <view style="width: 100%;padding-left: 10rpx;"><u-button style="width: 100%;" @click="onConfirmBtn(1)" :disabled="ruleForm.auditState === 1" :loading="confirmLoading" size="large" type="success">确认调拨出库</u-button></view>
		</view>
		<u-datetime-picker
            v-model="selectDateTime"
            :show="selectDateTimePickerState"
            mode="datetime"
			:closeOnClickOverlay="true"
            @confirm="onConfirmBtnOfSelectPicker"
            @close="onCloseBtnOfSelectPicker"
			@cancel="onCloseBtnOfSelectPicker"
        ></u-datetime-picker>
        <jkPopupOption
            :showAll="false"
            :value="selectProductItemWarehouseId"
            :show="selectWarehousePopupOptionState"
            :optionList="warehouseList"
            @visible-change="(e) => selectWarehousePopupOptionState = e"
            @confirm="onConfirmOfSelectWarehouse"
        ></jkPopupOption>
        <jkPopupOption
            :value="ruleForm.customerId"
            :show="selectCustomerPopupOptionState"
            :optionList="customerList"
            @visible-change="(e) => selectCustomerPopupOptionState = e"
            @confirm="onConfirmOfSelectCustomer"
        ></jkPopupOption>
	</scroll-view>
</template>

<script>
import {
    productionPackagePlanGet,
    productionStockTransferRecordCreate, productionStockTransferRecordDelete,
    productionStockTransferRecordGet,
    productionStockTransferRecordUpdate,
    spinCustomerPage,
    yongYouInventoryProductStockTotal,
    yongYouWarehouseList
} from "../../../../api";
import {
    formatDate,
    formatTime,
    showLoading, tipBar
} from "../../../../utils/jk-utils";
        import jkPopup from '../../../../jk-components/jk-popup';
    import jkFormCard from "../../../../jk-components/jk-from-card";
    import jkFormItem from "../../../../jk-components/jk-from-item";
    import jkPopupOption from "../../../../jk-components/jk-popup-option";
import getNoticeBatchInfo from "../packagePlan/getNoticeBatchInfo";
	export default {
        mixins: [getNoticeBatchInfo],
        components: {
            jkPopupOption,
            jkFormCard,
            jkFormItem,
			jkPopup
		},
		data() {
			return {
                selectWarehouseFrom: 'out',
                customerList: [],
                selectCustomerPopupOptionState: false,
                selectProductItemWarehouseId: null,
                selectWarehousePopupOptionState: false,
                warehouseList: [],
				selectDateTime: '',
				selectDateTimePickerState: false,
				confirmLoading: false,
                saveLoading: false,
				dataId: null,
                selectProductItemIndex: null,
                defaultProductItem: {
                    "batchCode": "",
                    "batchId": 0,
                    "beforeNumber": 0,
                    "bundleList": [],
                    "empCode": "",
                    "empId": 0,
                    "empName": "",
                    "innerBagList": [],
                    "invalidDateTime": "",
                    "number": 0,
                    "outerBagList": [],
                    "packingPlanCode": "",
                    "packingPlanId": 0,
                    "paperTubeList": [],
                    "productCode": "",
                    "productId": 0,
                    "productName": "",
                    "productionDateTime": "",
                    "remark": "",
                    "suttle": 0,
                    "type": 0,
                    "warehouseId": '',
                    "warehouseCode": '',
                    "warehouseName": '',
                    "workshopCode": "",
                    "workshopId": 0,
                    "workshopName": ""
                },
				ruleForm: {
                    auditState: 0,
                    stockTransferRecordList: [],
                    customerId: '',
                    customerCode: '',
                    customerName: '',
                    belongDateTime: '',
                    outWarehouseId: '',
                    outWarehouseCode: '',
                    outWarehouseName: '',
                    inWarehouseId: '',
                    inWarehouseCode: '',
                    inWarehouseName: '',
                    remark: ''
                },
			}
		},
		onLoad(e) {
            this.dataId = e.id;
            this.getDependentData();
        },
		onShow() {
		},
		methods: {
            onSelectProduct(index) {
                this.selectProductItemIndex = index;
                uni.navigateTo({
                    url: '/pages/production/packagePrd/outWarehouse/searchNotice'
                });
            },
            onSeeMoreBtn(item) {
                let str = '';
                str+= `纸管:${item.paperTubeList && item.paperTubeList.length ? item.paperTubeList.map(x => x.name).join() : '无'};`;
                str+= `内袋:${item.innerBagList && item.innerBagList.length ? item.innerBagList.map(x => x.name).join() : '无'};`;
                str+= `外袋:${item.outerBagList && item.outerBagList.length ? item.outerBagList.map(x => x.name).join() : '无'}`;
                wx.showModal({
                    title: '更多信息',
                    content: str,
                    showCancel: false,
                    confirmText: '关闭'
                });
            },
            onDeleteBtn() {
                let _this = this;
                uni.showModal({
                    title: '提示',
                    content: `确定删除调拨单吗？`,
                    success(res) {
                        if (res.confirm) {
                            productionStockTransferRecordDelete({id: _this.dataId}).then(res => {
                                if (res.data.status === 200) {
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }
                            });
                        }
                    }
                });
            },
            onConfirmOfSelectCustomer(e, item) {
                this.$set(this.ruleForm, 'customerId', item.id);
                this.$set(this.ruleForm, 'customerCode', item.code);
                this.$set(this.ruleForm, 'customerName', item.name);
                this.selectCustomerPopupOptionState = false;
            },
            onAddProductBtn() {
                if (this.ruleForm.outWarehouseId) {
                    this.ruleForm.stockTransferRecordList.push(JSON.parse(JSON.stringify(this.defaultProductItem)))
                } else {
                    tipBar('custom', '输出仓库不能空', 'error')
                }
            },
		    onClearPlanCode(index) {
                this.$set(this.ruleForm.stockTransferRecordList[index], 'packingPlanId', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'packingPlanCode', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'productId', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'productCode', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'productName', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'batchId', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'batchCode', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'categoryId', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'categoryCode', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'categoryName', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'customerId', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'customerCode', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'customerName', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'workshopId', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'workshopCode', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'workshopName', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'number', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'belongDate', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'ingredient', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'suttle', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'outNumber', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'beforeNumber', '');
                this.$set(this.ruleForm.stockTransferRecordList[index], 'remark', '');

                this.$set(this.ruleForm.stockTransferRecordList[index], 'outerBagList', []);
                this.$set(this.ruleForm.stockTransferRecordList[index], 'innerBagList', []);
                this.$set(this.ruleForm.stockTransferRecordList[index], 'paperTubeList', []);
                this.$set(this.ruleForm.stockTransferRecordList[index], 'bundleList', []);
            },
            onBlurPlanCode(e, index) {
                this.selectProductItemIndex = index;
                this.getData(e);
            },
            onSelectWarehouse(from) {
                this.selectWarehouseFrom = from;
                if (from === 'out') {
                    this.$set(this.ruleForm, 'stockTransferRecordList', []);
                    this.selectProductItemWarehouseId = this.ruleForm.outWarehouseId;
                } else {
                    this.selectProductItemWarehouseId = this.ruleForm.inWarehouseId;
                }
                this.selectWarehousePopupOptionState = true;
            },
            onClearOutWarehouse() {
                this.selectWarehouseFrom = 'out';
                this.onConfirmOfSelectWarehouse(null, {});
            },
            onConfirmOfSelectWarehouse(e, item) {
                if (this.selectWarehouseFrom === 'out') {
                    this.$set(this.ruleForm, 'outWarehouseId', item.id);
                    this.$set(this.ruleForm, 'outWarehouseCode', item.code);
                    this.$set(this.ruleForm, 'outWarehouseName', item.name);
                } else {
                    this.$set(this.ruleForm, 'inWarehouseId', item.id);
                    this.$set(this.ruleForm, 'inWarehouseCode', item.code);
                    this.$set(this.ruleForm, 'inWarehouseName', item.name);
                }
                this.selectWarehousePopupOptionState = false;

            },
            onSelectTime(type) {
                this.timeType = type;
                this.selectDateTimePickerState = true;
            },
            onScanBtn(index) {
                this.selectProductItemIndex = index;
                let _this = this;
                // 允许从相机和相册扫码
                uni.scanCode({
                    success: function (res) {
                        let scanData = '';
                        try {
                            scanData = res.result;
                        } catch {
                            wx.showToast({
                                title: '无效的二维码',
                                icon: 'error'
                            })
                        }
                        if (scanData) {
                            wx.showModal({
                                title: '扫码结果',
                                content: `通知单:${scanData}`,
                                success(res) {
                                    if (res.confirm) {
                                        _this.getData(scanData);
                                    }
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '二维码格式不符',
                                icon: 'error'
                            })
                        }
                    }
                });

            },
            getData(scanData) {
                this.getNoticeDetailRequest(scanData).then(res => {
                    if (res.data.status === 200) {
                        let resData = this.transferData(res.data.res);
                        this.$set(this.ruleForm.stockTransferRecordList, this.selectProductItemIndex, resData);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'warehouseId', this.ruleForm.outWarehouseId);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'warehouseCode', this.ruleForm.outWarehouseCode);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'warehouseName', this.ruleForm.outWarehouseName);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'beforeNumber', '');
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'productionDateTime', formatTime(Date.now()));
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'invalidDateTime', '');
                        this.$delete(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'id');
                        this.getProductItemStockRequest();
                    }
                });
            },
            /*getPlanDetailRequest(code) {
                return productionPackagePlanGet({ code }).then(res => {
                    if (res.data.status === 200) {
                        let resData = res.data.res || {};
                        this.$set(this.ruleForm.stockTransferRecordList, this.selectProductItemIndex, resData);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'warehouseId', this.ruleForm.outWarehouseId);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'warehouseCode', this.ruleForm.outWarehouseCode);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'warehouseName', this.ruleForm.outWarehouseName);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'beforeNumber', '');
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'productionDateTime', formatTime(Date.now()));
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'invalidDateTime', '');
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'packingPlanId', resData.id);
                        this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'packingPlanCode', resData.code);
                        this.$delete(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'id');
                        this.getProductItemStockRequest();
                        if (!resData) {
                            wx.showToast({
                                title: '无效的二维码',
                                icon: 'error'
                            })
                        }
                    }
                });
            },*/
            getDetailRequest() {
                return productionStockTransferRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        let resData = res.data.res || {};
                        resData.stockTransferRecordList = resData.stockTransferRecordList ? resData.stockTransferRecordList : [];
                        this.ruleForm = resData;
                    }
                });
            },
            onTransferNumber(e, type, index) {
                this.$set(this.ruleForm.stockTransferRecordList[index], type, Number(e));
            },
			onCloseBtnOfSelectPicker() {
				this.selectDateTimePickerState = false;
			},
			onConfirmBtnOfSelectPicker(e) {
				this.$set(this.ruleForm, this.timeType, formatTime(e.value));
				this.selectDateTimePickerState = false;
			},
			onConfirmBtn(e) {
                let params = JSON.parse(JSON.stringify(this.ruleForm));
                params.belongDate = params.belongDateTime ? formatDate(params.belongDateTime) : '';
                params.auditState = e;
                // let hasNull = this.ruleForm.stockTransferRecordList.some(x => !x.outNumber || x.outNumber > x.beforeNumber || !x.packingPlanCode);
                let hasNull = this.ruleForm.stockTransferRecordList.some(x => !x.outNumber || !x.packingPlanCode);
                let api = this.dataId ? productionStockTransferRecordUpdate : productionStockTransferRecordCreate;
                if (!hasNull && params.outWarehouseId && params.inWarehouseId && this.ruleForm.stockTransferRecordList && this.ruleForm.stockTransferRecordList.length) {
                    if (!e) {
                        this.saveLoading = true;
                    } else {
                        this.confirmLoading = true;
                    }
                    api(params).then(res => {
                        if (!e) {
                            this.saveLoading = false;
                        } else {
                            this.confirmLoading = false;
                        }
                        if (res.data.status === 200) {
                            uni.navigateBack({
                                delta: 1
                            });
                            tipBar('save');
                        }
                    })
                } else {
                    uni.showToast({
                        title: '请填写完成',
                        icon: 'error'
                    });
                }
			},
            getWarehouseListRequest() {
                return yongYouWarehouseList().then(res => {
                    if (res.data.status === 200) {
                        this.warehouseList = res.data.res;
                    }
                });
            },
            getCustomerListRequest() {
                return spinCustomerPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.customerList = res.data.res;
                    }
                });
            },
            getProductItemStockRequest() {
                if (this.ruleForm.outWarehouseCode && this.ruleForm.stockTransferRecordList[this.selectProductItemIndex].productId && this.ruleForm.stockTransferRecordList[this.selectProductItemIndex].batchCode) {
                    return yongYouInventoryProductStockTotal({
                        warehouseCode:  this.ruleForm.outWarehouseCode,
                        productId:  this.ruleForm.stockTransferRecordList[this.selectProductItemIndex].productId,
                        batchCode:  this.ruleForm.stockTransferRecordList[this.selectProductItemIndex].batchCode,
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.$set(this.ruleForm.stockTransferRecordList[this.selectProductItemIndex], 'beforeNumber', res.data.res.availableQuantity ? parseFloat(res.data.res.availableQuantity) : 0);
                        }
                    });
                }
            },
			async getDependentData() {
                this.$set(this.ruleForm, 'belongDateTime', formatTime(Date.now()));
                showLoading(true);
				this.selectDateTime = formatTime(Date.now());
                await this.getWarehouseListRequest();
                await this.getCustomerListRequest();
				if (this.dataId) await this.getDetailRequest();
				showLoading(false);
			}
		}
	}
</script>

<style>

</style>
<style lang="scss" scoped>
	.machine-title {
		height: 42px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2d8cf0;
		border-radius: 12rpx;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
        border: solid 1px #2d8cf0;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		margin: 10rpx;
	}
	.popup-content-box {
		padding: 32rpx;
		.popup-content-box-title {
			font-size: 34rpx;
			text-align: center;
			margin-bottom: 20rpx;
		}
	}
</style>
